package cn.zz.veggie.application.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.core.types.result.PageResult;
import cn.zz.comm.types.result.R;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.application.assembler.AdminAssembler;
import cn.zz.veggie.application.helper.AdminHelper;
import cn.zz.veggie.application.packer.AdminPacker;
import cn.zz.veggie.model.domain.Admin;
import cn.zz.veggie.model.query.AdminQuery;
import cn.zz.veggie.persistence.repository.AdminAuthRepository;
import cn.zz.veggie.persistence.repository.AdminRepository;
import cn.zz.veggie.web.types.dto.mgmt.MgmtAdminLoginDto;
import cn.zz.veggie.web.types.dto.mgmt.admin.MgmtAdminQueryDto;
import cn.zz.veggie.web.types.vo.LoginTokenVo;
import cn.zz.veggie.web.types.vo.mgmt.admin.MgmtAdminVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongq
 * @since 2024/5/13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminAppService {

	private final AdminRepository adminRepository;
	private final AdminAuthRepository adminAuthRepository;

	public R<LoginTokenVo> adminLogin(MgmtAdminLoginDto dto) {
		Admin admin = adminRepository.findByMobile(dto.getUsername());
		AdminHelper.matchByLogin(admin, dto.getUsername(), dto.getPassword());
		// gen token
		String token = adminAuthRepository.genAdminLoginToken(admin);
		// user login action
		return R.ok(new LoginTokenVo(token));
	}

	public PageResult<MgmtAdminVo> adminGetAdminList(MgmtAdminQueryDto dto, PageQuery page) {
		AdminQuery query = AdminAssembler.buildQuery(dto);
		List<Admin> admins = adminRepository.findByPage(query, page);
		return PageResult.of(page, CollectorUtil.bwl(admins, AdminPacker::toMgmtAdminVo));
	}
}